/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.thrift.server;

import com.vng.zing.survey.utility.Config;
import com.vng.zing.survey.thrift.service.SurveyService;
import com.vng.zing.survey.utility.TimeDay;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import org.apache.log4j.Logger;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;

/**
 *
 * @author kienpd
 */
public class SurveyServiceMain {

    private static Logger logger = Logger.getLogger(SurveyServiceMain.class);

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException, ParseException {
//        //   TODO code application logic here
        Timer timer = new Timer();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        String today = TimeDay.dateToString(new Date());
        today += " " + Config.getParamStr("schedule_date", "date");
        Date date = formatter.parse(today);
        if (date.getTime() < new Date().getTime()) {
            date = TimeDay.nextDay(date);
            System.out.println(date.toString());
        }
        timer.schedule(new Statistic(), date, Config.getParamInt("schedule_date", "delay"));

        int thriftPort = Config.getParamInt("thrift_server", "port");
        SurveyServiceHandler handler = new SurveyServiceHandler();//tu tao
        TProcessor p = new SurveyService.Processor((SurveyService.Iface) handler);
        final TServer server;
        try {
            TServerTransport serverTransport = new TServerSocket(thriftPort);
            server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).transportFactory(new TFramedTransport.Factory()).protocolFactory(new TBinaryProtocol.Factory()).processor(p).minWorkerThreads(10).maxWorkerThreads(30));

//           TNonblockingServerTransport st = new TNonblockingServerSocket(thriftPort);
//            server = new TNonblockingServer(new TNonblockingServer.Args(st).processor(p));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("WebServer:startThriftServer:err = " + e.getMessage(), e);
            return;
        }
        //  logger.info("Thrift server start!");
        server.serve();

    }
}
